package com.wlz.controller;

import com.wlz.model.Article;
import com.wlz.resp.JsonResult;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.elasticsearch.core.ElasticsearchOperations;
import org.springframework.data.elasticsearch.core.SearchHit;
import org.springframework.data.elasticsearch.core.SearchHits;
import org.springframework.data.elasticsearch.core.query.NativeSearchQuery;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;
import java.util.stream.Collectors;

/**
 * @author： wlz
 * @Date 2020/12/23 18:43
 * @description： TODO
 * @version: 1.0
 */

@RestController
@RequestMapping("articleOperations")
public class ArticleOperationsController {

    @Autowired
    ElasticsearchOperations elasticsearchOperations;


    @GetMapping("list")
    public JsonResult list(Integer currentPage, Integer limit) {
        if (currentPage == null || currentPage < 0 || limit == null || limit <= 0) {
            return new JsonResult(false, "请输入合法的分页参数");
        }
        // 分页列表查询
        // 旧版本的 Repository 中的 search 方法被废弃了。
        // 这里采用 ElasticSearchRestTemplate 或 ElasticsearchOperations 来进行分页查询

        JsonResult jsonResult = new JsonResult(true);
        NativeSearchQuery query = new NativeSearchQuery(new BoolQueryBuilder());
        query.setPageable(PageRequest.of(currentPage, limit));

        // 方法1：
//        SearchHits<Article> searchHits = elasticsearchRestTemplate.search(query, Article.class);

        // 方法2：
         SearchHits<Article> searchHits = elasticsearchOperations.search(query, Article.class);

        // 方法3：
        // 在方法上加 @Query 注解，其中手写查询语句 —— 有点难度，不会写

        List<Article> articles = searchHits.getSearchHits().stream().map(SearchHit::getContent).collect(Collectors.toList());
        jsonResult.put("count", searchHits.getTotalHits());
        jsonResult.put("articles", articles);
        return jsonResult;
    }

}
